<?php

namespace Core\Log\Driver;

class Mongo {

    protected $config  =   array(
        'host' => '10.3.105.101',
        'port' => 27017,
        'user' => '',
        'password' => '',
        'database' => 'php_log',
        'col' => 'php_log'
    );
    
    // 实例化并传入参数
    public function __construct($config=array()){
        if (empty($config)){
            $config = C("mongo.log");
            $this->config['host'] = $config['host'];
            $this->config['port'] = $config['port'];
            $this->config['user'] = $config['user'];
            $this->config['password'] = $config['password'];
            $this->config['database'] = $config['database'];
            $this->config['col'] = $config['col'];
        } else {
            $this->config   =   array_merge($this->config,$config);
        }
    }

    /**
     * 日志写入接口
     * 
     * @access public
     * @param string $log 日志信息
     * @param string $destination 写入目标
     * @return void
     */
    public function write($log, $destination = '')
    {
        $config = $this->config;
        $host = 'mongodb://'.($config['user']?"{$config['user']}":'').($config['password']?":{$config['password']}@":'').$config['host'].($config['port']?":{$config['port']}":'').'/'.($config['database']?"{$config['database']}":'');
        $conn = new mongoClient($host);
        $mongodb = $conn->selectDb($this->config['database']);
        $collection = $mongodb->$config['col'];
        
        $raw = file_get_contents('php://input');
        $post = json_encode($_POST);
        $get = json_encode($_GET);
        $cookie = json_encode($_COOKIE);
        if (!empty($_COOKIE['tokenvals'])){
            $redis = redis();
            $cookie_date = $redis->get($_COOKIE['tokenvals']);
            if (empty($cookie_date)){
                $user_id = intval(0);
            } else {
                $login_item = explode(":", $cookie_date);
                $user_id = intval($login_item[1]);                
            }
        } else {
            $user_id = intval(0);
        }
        $data = array(
            "user_id" => $user_id,
            "ip" => $_SERVER['REMOTE_ADDR'],
            "url" => $_SERVER['REQUEST_URI'],
            "raw" => $raw,
            "post" => $post,
            "get" => $get,
            "cookie" => $cookie,
            "content" => json_encode($log),
            "addtime" => date("Y-m-d H:i:s")
        );
        $collection->insert($data);
    }
}

